<template>
  <div>
    <el-input
        v-model="searchTitle"
        placeholder="请输入标题"
        @keyup.enter="searchFm"
    >
      <template #append>
        <el-button @click="searchFm">查询</el-button>
      </template>
    </el-input>
    <el-button type="primary" @click="showAddDialog">添加</el-button>
    <el-button type="danger" @click="batchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
    <el-table
        :data="fmList"
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="img" label="图片" width="100">
        <template #default="scope">
          <img :src="getImgUrl(scope.row.img)" alt="图片" width="80" />
        </template>
      </el-table-column>
      <el-table-column prop="introduction" label="简介" />
      <el-table-column prop="text" label="内容" />
      <el-table-column prop="consultantsId" label="咨询师 ID" width="100" />
      <el-table-column prop="time" label="时间" width="180" />
      <el-table-column prop="collection" label="收藏量" />
      <el-table-column prop="read" label="阅读量" />
      <el-table-column prop="favorate" label="是否精选" />
      <el-table-column prop="type" label="类别" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="showDetailDialog(scope.row)">详情</el-button>
          <el-button size="small" type="warning" @click="showEditDialog(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="deleteFm(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />

    <!-- 添加/修改弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '修改 文章信息' : '添加 文章信息'"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              action="/api/oss/upload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              @success="handleAvatarSuccess"
          >
            <template #trigger>
              <img :src="getImgUrl(form.img)" alt="picture" style="width: 100px">
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.introduction" type="textarea" />
        </el-form-item>

        <el-form-item label="内容">
          <el-input v-model="form.text" type="textarea" />
        </el-form-item>
        <el-form-item label="咨询师 ID">
          <el-input v-model="form.consultantsId" type="number" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker
              v-model="form.time"
              type="datetime"
              placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="收藏量">
          <el-input v-model="form.collection" />
        </el-form-item>
        <el-form-item label="阅读量">
          <el-input v-model="form.read" />
        </el-form-item>
        <el-form-item label="是否精选">
          <el-input v-model="form.favorate" />
        </el-form-item>
        <el-form-item label="文章类别">
          <el-input v-model="form.type" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="FM 信息详情"
    >
      <el-form :model="detailForm" label-width="100px">
        <el-form-item label="标题">
          <span>{{ detailForm.title }}</span>
        </el-form-item>
        <el-form-item label="图片">
          <img :src="getImgUrl(detailForm.img)" alt="图片" width="200" />
        </el-form-item>
        <el-form-item label="简介">
          <span>{{ detailForm.introduction }}</span>
        </el-form-item>

        <el-form-item label="内容">
          <span>{{ detailForm.text }}</span>
        </el-form-item>
        <el-form-item label="咨询师 ID">
          <span>{{ detailForm.consultantsId }}</span>
        </el-form-item>
        <el-form-item label="时间">
          <span>{{ detailForm.time }}</span>
        </el-form-item>
        <el-form-item label="收藏量">
          <span>{{ detailForm.collection }}</span>
        </el-form-item>
        <el-form-item label="阅读量">
          <span>{{ detailForm.read }}</span>
        </el-form-item>
        <el-form-item label="是否精选">
          <span>{{ detailForm.favorate }}</span>
        </el-form-item>
        <el-form-item label="文章类别">
          <span>{{ detailForm.type }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import axios from 'axios';
// 日期格式化函数
const formatDate = (date) => {
  if (!date || typeof date.getFullYear!== 'function') {
    return null;
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


// 搜索关键词
const searchTitle = ref('');
// 文章 列表
const fmList = ref([]);
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总数量
const total = ref(0);
// 选中的 ID 列表
const selectedIds = ref([]);
// 添加/修改弹窗是否显示
const dialogVisible = ref(false);
// 详情弹窗是否显示
const detailDialogVisible = ref(false);
// 是否为编辑状态
const isEdit = ref(false);
// 表单数据
const form = ref({
  id: null,
  title: '',
  img: '',
  introduction: '',
  text: '',
  consultantsId: null,
  time: null,
  collection: '',
  read: '',
  favorate: '',
  type: '',

});
// 详情数据
const detailForm = ref({});

// 获取 文章 列表
const getFmList = async () => {
  try {
    const response = await axios.get('/api/featuredArticles/findByTitle', {
      params: {
        title: searchTitle.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    });
    fmList.value = response.data.data.list;
    total.value = response.data.data.total;
  } catch (error) {
    console.error('获取 文章 列表失败', error);
  }
};

// 搜索 文章
const searchFm = () => {
  currentPage.value = 1;
  getFmList();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getFmList();
};

// 处理当前页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getFmList();
};

// 处理表格选择变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id);


};

// 显示添加弹窗
const showAddDialog = () => {
  isEdit.value = false;
  form.value = {
    id: null,
    title: '',
    img: '',
    introduction: '',
    filename: '',
    text: '',
    consultantsId: null,
    time: null,
    collection: '',
    read: '',
    favorate: '',
    type: '',
  };
  dialogVisible.value = true;
};

// 显示编辑弹窗
const showEditDialog = (row) => {
  isEdit.value = true;
  form.value = { ...row };
  dialogVisible.value = true;
};

// 显示详情弹窗
const showDetailDialog = (row) => {
  detailForm.value = { ...row };
  detailDialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    //格式化日期
    if (form.value.time) {
      form.value.time = formatDate(form.value.time);
    }
    let response;
    if (isEdit.value) {
      response = await axios.put('/api/featuredArticles', form.value);
    } else {
      response = await axios.post('/api/featuredArticles', form.value);
    }
    if (response.data.code === 200) {
      dialogVisible.value = false;
      await getFmList();
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功');
    } else {
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
    }
  } catch (error) {
    console.error(isEdit.value ? '修改失败' : '添加失败', error);
    ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
  }
};

// 删除 FM
const deleteFm = async (id) => {
  try {
    const confirm = await ElMessageBox.confirm('确定要删除该 文章 信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if (confirm) {
      const response = await axios.delete(`/api/featuredArticles/${id}`);
      if (response.data.code === 200) {
        await getFmList();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    }
  } catch (error) {
    if (error.type !== 'cancel') {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }
};

// 批量删除
const batchDelete = async () => {
  try {
    const confirm = await ElMessageBox.confirm('确定要批量删除选中的 文章 信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if (confirm) {
      console.log(selectedIds.value);
      const response = await axios.delete('/api/featuredArticles/batch', {
        data:
        selectedIds.value
      });
      if (response.data.code === 200) {
        await getFmList();
        selectedIds.value = [];
        ElMessage.success('批量删除成功');
      } else {
        ElMessage.error('批量删除失败');
      }
    }
  } catch (error) {
    if (error.type !== 'cancel') {
      console.error('批量删除失败', error);
      ElMessage.error('批量删除失败');
    }
  }
};
const beforeAvatarUpload = (file) => {
  // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  // if (!isJpgOrPng) {
  //   ElMessage.error('只能上传 JPG/PNG 格式的图片！');
  // }
  // const isLt2M = file.size / 1024 / 1024 < 2;
  // if (!isLt2M) {
  //   ElMessage.error('图片大小不能超过 2MB！');
  // }
  // return isJpgOrPng && isLt2M;
};
const handleAvatarSuccess = (response, file) => {
  if (response) {
    form.value.img = response;

    ElMessage.success('图片上传成功！');
  } else {
    ElMessage.error('图片上传失败！');
  }
};

const getImgUrl = (img) => {
  return img;
}
onMounted(() => {
  getFmList();
});
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>